/*
 * 天虹商场股份有限公司版权所有.
 */
package com.rainbow.mybatis.config;

import com.rainbow.mybatis.executor.CachingExecutor;
import com.rainbow.mybatis.executor.Executor;
import com.rainbow.mybatis.executor.SimpleExecutor;
import com.rainbow.mybatis.plugin.Interceptor;
import com.rainbow.mybatis.plugin.InterceptorChain;
import com.rainbow.mybatis.result.ResultSetHandler;
import com.rainbow.mybatis.statement.SimpleStatementHandler;
import com.rainbow.mybatis.statement.StatementHandler;
import lombok.Data;

import java.io.IOException;
import java.util.List;
import java.util.Properties;

/**
 * TODO
 *
 * @author 黄明坤
 * @version 1.0.0
 * @date 2020/6/23
 */
@Data
public class Configuration {

    /**
     * 接口路径
     */
    private String scanPath;

    protected final InterceptorChain interceptorChain = new InterceptorChain();


    public void addInterceptor(Interceptor interceptor) {
        interceptorChain.addInterceptor(interceptor);
    }

    /**
     * 接口列注册的成员变量
     */
    private MapperRegistory mapperRegistory = new MapperRegistory();

    public Configuration scanPath(String scanPath) {
        this.scanPath = scanPath;

        return this;
    }

    /**
     * 构建这个配置类
     * @throws IOException
     */
    public void build(List<Interceptor> interceptors) throws IOException {
        if (null == scanPath || scanPath.length() < 1) {
            throw new RuntimeException("scan path is required .");
        }
        if(null != interceptors){
            interceptors.stream().forEach(interceptor -> {
                interceptor.setProperties(new Properties());
                this.addInterceptor(interceptor);
            });
        }
    }

    public static void main(String[] args) throws IOException {
        //new Configuration().scanPath("com/rainbow/mapper").build();
    }

    private static final String SIMPLE = "SIMPLE";
    private static final String CACHING = "CACHING";

    public Executor newExecutor(String key,Configuration configuration) {
        Executor executor = null;
        if (SIMPLE.equalsIgnoreCase(key)) {
            executor = new SimpleExecutor(configuration);
        }
        if (CACHING.equalsIgnoreCase(key)) {
            executor = new CachingExecutor(new SimpleExecutor(configuration));
        }

        //创建一个代理对象
        executor = (Executor) interceptorChain.pluginAll(executor);
        return executor;
    }

    public StatementHandler newStatementHandler(Configuration configuration) {
        StatementHandler statementHandler = new SimpleStatementHandler(configuration);
        statementHandler = (StatementHandler) interceptorChain.pluginAll(statementHandler);
        return statementHandler;
    }

}